﻿using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Model.UI;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Telerik.Windows.Data;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class HookUpViewModel : DynamicColumnRegionViewModel
    {
        private string _cadFile;
        private TreeNodeModelList _nodes;
        private readonly IHookUpService _hookUpService;
        private readonly ITemplateSettingService _tempService;
        private DelegateCommand<object> _selectChangedCommand;
        private dynamic _hookUps;
        private ObservableCollection<HookUpItemList> _hookUpItemLists;

        private List<DynamicPropertyInfo> _hookUpItemPropertyInfos;
        private List<DynamicPropertyInfo> _hookUpsPropertyInfos;
        private RadObservableCollection<GridViewColumn> _hookUpsColumns;
        private RadObservableCollection<GridViewColumn> _hookUpItemcolumns;

        public HookUpViewModel(
            IRegionManager regionManager,
            IUnityContainer unityContainer,
            IDialogService dialogService,
            IHookUpService hookUpService,
            ITemplateSettingService achievementService) :
            base(regionManager, unityContainer, dialogService)
        {
            _tempService = achievementService;
            _hookUpService = hookUpService;
            _nodes = new TreeNodeModelList();

            _hookUpItemLists = new ObservableCollection<HookUpItemList>();
            _hookUps = new ObservableCollection<Instruments>();
        }

        #region OVERRIDE
        protected override void LoadPropertyInfos()
        {
            _hookUpsPropertyInfos = new List<DynamicPropertyInfo>();
            _hookUpItemPropertyInfos = new List<DynamicPropertyInfo>();
            var columns = GlobalObject.HookUpItemPropertyInfos;

            _hookUpItemPropertyInfos.Clear();
            _hookUpItemPropertyInfos.AddRange(columns);

            var componentColumns = GlobalObject.HookUpComponentPropertyInfos;
            _hookUpsPropertyInfos.Clear();
            _hookUpsPropertyInfos.AddRange(componentColumns);
        }

        protected override async void OnInitPage(object obj)
        {
            var treeData = await _hookUpService.GetHookUpTypeTreeAsync(GlobalObject.CurrentProject.ProjId.ToString());

            TreeNodes.Clear();
            if (treeData == null) return;
            if (treeData.Count < 1) return;

            var trees = new TreeNodeModelList();
            trees.BeginUpdate();
            foreach (var item in treeData)
            {
                var node = new TreeNodeModel(trees, null)
                {
                    NodeName = item.HuTypeName,
                    Id = item.HuTypeId.ToString(),
                    IconGlyph = "&#xe51a;",
                    NodeType = TreeNodeType.HookUpType
                };
                if (item.HookUpList != null && item.HookUpList.Count > 0)
                {
                    foreach (var hookUp in item.HookUpList)
                    {
                        var hookUpNode = new TreeNodeModel(trees, null)
                        {
                            NodeName = hookUp.HuName,
                            Id = hookUp.HuId.ToString(),
                            IconGlyph = "&#xe51b;",
                            NodeType = TreeNodeType.HookUp
                        };
                        node.Nodes.Add(hookUpNode);
                    }
                }
                trees.Add(node);
            }
            trees.EndUpdate();
            TreeNodes = trees;
        }
        #endregion

        #region PROP
        public ICommand SelectChangedCommand
        {
            get
            {
                if (_selectChangedCommand != null) return _selectChangedCommand;
                _selectChangedCommand = new DelegateCommand<object>(onSelectChangedCommandAsync);
                return _selectChangedCommand;
            }
        }

        /// <summary>
        /// 获取动态表格列。
        /// </summary>
        public RadObservableCollection<GridViewColumn> HookUpItemColumns
        {
            get
            {
                if (_hookUpItemcolumns != null)
                    return _hookUpItemcolumns;
                _hookUpItemcolumns = GetGridColumns(_hookUpItemPropertyInfos);
                return _hookUpItemcolumns;
            }
            set
            {
                SetProperty(ref _hookUpItemcolumns, value);
            }
        }

        /// <summary>
        /// 获取动态表格列。
        /// </summary>
        public RadObservableCollection<GridViewColumn> HookUpsColumns
        {
            get
            {
                if (_hookUpsColumns != null)
                    return _hookUpsColumns;
                _hookUpsColumns = GetGridColumns(_hookUpsPropertyInfos);
                return _hookUpsColumns;
            }
            set
            {
                SetProperty(ref _hookUpsColumns, value);
            }
        }

        public ObservableCollection<HookUpItemList> HookUpItemLists
        {
            get
            {
                return _hookUpItemLists;
            }
            set { SetProperty(ref _hookUpItemLists, value); }
        }

        public dynamic HookUps
        {
            get
            {
                return _hookUps;
            }
            set { SetProperty(ref _hookUps, value); }
        }

        public TreeNodeModelList TreeNodes
        {
            get
            {
                return _nodes;
            }
            set { SetProperty(ref _nodes, value); }
        }

        public string CADFile
        {
            get
            {
                return _cadFile;
            }
            set { SetProperty(ref _cadFile, value); }
        }
        #endregion

        private async void onSelectChangedCommandAsync(object sender)
        {
            HookUps.Clear();
            HookUpItemLists.Clear();
            var args = sender as System.Windows.Controls.SelectionChangedEventArgs;
            if (args == null) return;
            if (args.AddedItems.Count < 1) return;

            var obj = args.AddedItems[0] as TreeNodeModel;
            if (obj == null) return;
            if (obj.NodeType != TreeNodeType.HookUp) return;

            var proId = GlobalObject.CurrentProject.ProjId.ToString();
            //var hookUpList = await _hookUpService.GetHookUpAsync(proId, obj.Id);

            var hookUpDetailList = await _hookUpService.GetHookUpDetailAsync(proId, obj.Id);
            if (hookUpDetailList != null && hookUpDetailList.components.IsNotEmptyOrNull())
            {
                var jsonStr = hookUpDetailList.components.Serialize();
                dynamic dynamicObj = await _hookUpService.LoadDynamicHookUpComponents(jsonStr);
                HookUps = dynamicObj;
            }

            if (hookUpDetailList != null && hookUpDetailList.ItemLists != null)
                HookUpItemLists.AddRange(hookUpDetailList.ItemLists);

            if (hookUpDetailList != null && hookUpDetailList.HuBlockName.IsNotEmptyOrNull())
            {
                try
                {
                    CADFile = await DownLoadDwgFile(hookUpDetailList.HuBlockName);
                }
                catch (Exception x)
                {
                    var msg = $"下载DWG文件失败：{x.Message}";
                    Dialog.ShowAltert(msg);
                    LoggerHelper.Current.Error(msg, x);
                    return;
                }
            }
        }

        private async Task<string> DownLoadDwgFile(string dwgFile)
        {
            var report = new Report()
            {
                Name = dwgFile,
                Type = Model.TemplateType.HOOKUP,
                TemplatePath = ""
            };
            var r = await _tempService.DownloadTemplateFileAsync(GlobalObject.CurrentProject.ProjId.ToString(), report);
            if (!r.succeeded)
            {
                var error = r.errors != null ? r.errors.ToString() : "无任何错误信息返回！！";
                var msg = $"下载DWG文件失败：{error}";
                Dialog.ShowAltert(msg);
                LoggerHelper.Current.Error(msg);
                return "";
            }
            if (r.data != null)
            {
                dwgFile = AppDomain.CurrentDomain.BaseDirectory.CombinePath($"Data\\{dwgFile}");
                using var stream = r.data;
                await FileHelper.WriteFileStreamAsync(stream, dwgFile);
                return dwgFile;
            }
            return "";
        }
    }
}
